package com.mingtu.guards.activity;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.CustomDecoration;
import com.hjq.gson.factory.GsonFactory;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SpacesItemDecoration;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.WarningRecordAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.InfraredWarningBean;
import com.mingtu.guards.utils.MyConstant;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.mingtu.guards.utils.MyConstant.ItemDecorationSpaces;

public class WarningRecordActivity extends MyBaseActivity {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    @BindView(R.id.empty_layout)
    EmptyDataLayout emptyLayout;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_warning_type)
    TextView tvWarningType;
    @BindView(R.id.tv_warning_time)
    TextView tvWarningTime;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_no_data)
    TextView tvNoData;
    @BindView(R.id.layout_first)
    LinearLayout layoutFirst;
    private int currentPage = 1;
    private boolean isLoadMore = true;
    private WarningRecordAdapter warningRecordAdapter;
    private String firstUrl;
    private String firstCreatetime;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_warning_record;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("预警记录");
    }

    @Override
    protected void initData() {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new CustomDecoration(context, CustomDecoration.VERTICAL_LIST, R.drawable.shape_dive_line, 0));
        recycler.addItemDecoration(new SpacesItemDecoration(0, 0, 0, ItemDecorationSpaces, ItemDecorationSpaces));

        warningRecordAdapter = new WarningRecordAdapter();
        recycler.setAdapter(warningRecordAdapter);
//        warningRecordAdapter.isFirstOnly(false);
//        warningRecordAdapter.openLoadAnimation(SCALEIN);
        warningRecordAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener()  {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                InfraredWarningBean.PageBean.ListBean listBean = warningRecordAdapter.getData().get(position);
                if (listBean != null) {
                    String url = listBean.getUrl();
                    String createTime = listBean.getCreateTime();
                    eventDetails(url, createTime);
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getWarningList(1);
    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getWarningList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(warningRecordAdapter.getData(), Constant.PAGE_SIZE);
                    getWarningList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 预警记录列表
     */
    private void getWarningList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INF_WARNING_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            InfraredWarningBean infraredWarningBean = null;
                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                infraredWarningBean = new InfraredWarningBean();
                                infraredWarningBean = gson.fromJson(result, InfraredWarningBean.class);
                                List<InfraredWarningBean.PageBean.ListBean> dataBeans = infraredWarningBean.getPage().getList();

                                try {
                                    emptyLayout.setIsShowView(false);
                                    recycler.setVisibility(View.VISIBLE);


                                    if (dataBeans != null) {

                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        if (!isLoadMore) {
                                            if (currentPage > 1) {
                                                ToastUtils.showLong(getResources().getString(R.string.text_no_more_data));
                                            } else {
                                                if (dataBeans.size() == 0) {
                                                    //显示占位图
                                                    emptyLayout.setIsShowView(true);
                                                    recycler.setVisibility(View.GONE);
                                                }

                                            }
                                        }

                                        if (currentPage == 1) {

                                            if (dataBeans.size() > 1) {
                                                List<InfraredWarningBean.PageBean.ListBean> otherData = dataBeans.subList(1, dataBeans.size() - 1);
                                                warningRecordAdapter.replaceData(dataBeans);
                                                recycler.setVisibility(View.VISIBLE);
                                                tvNoData.setVisibility(View.GONE);
                                            } else {
                                                recycler.setVisibility(View.GONE);
                                                tvNoData.setVisibility(View.VISIBLE);
                                            }

                                            if (dataBeans.size() > 0) {
                                                List<InfraredWarningBean.PageBean.ListBean> firstData = dataBeans.subList(0, 1);
                                                InfraredWarningBean.PageBean.ListBean firstBean = firstData.get(0);

                                                String deviceName = firstBean.getDeviceName(); //设备名字
                                                firstCreatetime = firstBean.getCreateTime();
                                                String msgType = firstBean.getMsgType();
                                                String msgContent = firstBean.getMsgContent();
                                                firstUrl = firstBean.getUrl();

                                                if (!StringUtils.isEmpty(deviceName)) {
                                                    tvName.setText("设备编号：" + deviceName);
                                                }

                                                if (!StringUtils.isEmpty(firstCreatetime)) {
                                                    tvWarningTime.setText("报警时间：" + firstCreatetime);
                                                }

                                                if (!StringUtils.isEmpty(msgType)) {
                                                    tvWarningType.setText("报警类型：" + msgType);
                                                }

                                                if (!StringUtils.isEmpty(msgContent)) {
                                                    tvContent.setText("报警事件：" + msgContent);
                                                }

                                            }
                                        } else {
                                            warningRecordAdapter.addData(dataBeans);
                                        }
                                    } else {
                                        if (currentPage == 1) {
                                            //显示占位图
                                            recycler.setVisibility(View.GONE);
                                            emptyLayout.setIsShowView(true);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            } catch (JsonSyntaxException e) {

                                e.printStackTrace();
                                isLoadMore = false;
                                emptyLayout.setIsShowView(true);
                                recycler.setVisibility(View.GONE);
                                ToastUtils.showLong(getResources().getString(R.string.text_json_error));

                            }

                        }
                    }
                });
    }

    @OnClick({R.id.layout_first})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.layout_first:
                eventDetails(firstUrl, firstCreatetime);
                break;
        }
    }

    /**
     * 事件详情
     *
     * @param url
     * @param createTime
     */
    private void eventDetails(String url, String createTime) {
        if (!StringUtils.isEmpty(url)) {
            LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
            ArrayList<LocalMedia> localMediaList = new ArrayList<>();
            localMediaList.add(localMedia);
            BaseApplication.initPreviewModel().startActivityPreview(0, false, localMediaList);

        } else {
            ToastUtils.showLong("设备发生故障哦~");
        }
    }
}